package com.feihong.yw189.activity.yonghuzhongxin.wodexiaoxi;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.feihong.yw189.R;
import com.feihong.yw189.activity.base.BaseActivity;
import com.feihong.yw189.adapter.MyBaseAdapter;
import com.feihong.yw189.app.App;
import com.feihong.yw189.global.RequestTools;
import com.feihong.yw189.listener.http.RequestCallBack;
import com.feihong.yw189.message.LoginMessage;
import com.feihong.yw189.model.User.MessageItem;
import com.feihong.yw189.model.User.message.SystemMessageListModel;
import com.feihong.yw189.model.notice.StandLetterInfo;
import com.feihong.yw189.utils.CustomServiceUtil;
import com.holenzhou.pullrecyclerview.PullRecyclerView;
import com.holenzhou.pullrecyclerview.layoutmanager.XLinearLayoutManager;
import com.meiqia.meiqiasdk.imageloader.MQImage;
import com.meiqia.meiqiasdk.util.MQIntentBuilder;

import org.xutils.common.Callback;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import txgw.feihong.com.txgwlibrary.mqglide_loader.MQGlideImageLoader4;

public class MessageListActivity extends BaseActivity {

    @BindView(R.id.rl_goback)
    RelativeLayout ivBack;
    @BindView(R.id.txt_pagetitle)
    TextView txtPagetitle;
    @BindView(R.id.iv_lin)
    ImageView ivLin;
    @BindView(R.id.iv_confirm)
    TextView ivConfirm;
    @BindView(R.id.top_back_layout)
    LinearLayout topBackLayout;
    @BindView(R.id.takePlc)
    View takePlc;
    @BindView(R.id.pull_recycler_view)
    PullRecyclerView mPullRecyclerView;

    private MyBaseAdapter mAdapter;
    private Unbinder unbinder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_message_list);
        unbinder = ButterKnife.bind(this);

        initView();
        bindData();

    }

    @Override
    public void setTheme() {

    }

    public void initView() {
        setBackButtonFinish();
        setPageTitle("我的消息");
        ivLin.setVisibility(View.GONE);

    }

    private List<MessageItem> mDatas;
    public void bindData() {
        Map<String, Object> map = new HashMap();
        map.put("title", R.id.my_message_item_title);
        map.put("time", R.id.my_message_item_time);
        map.put("message", R.id.my_message_item_info);
        map.put("subTitle", R.id.my_message_item_num);
        map.put("imageResId", R.id.my_message_item_img);

        //初始数据
        // 设置LayoutManager（这里需要使用lib里面提供的XLinearLayoutManager或XGridLayoutManager，默认为XLinearLayoutManager）
        mPullRecyclerView.setLayoutManager(new XLinearLayoutManager(this));
        // 创建adapter，adapter的使用方法看后面
        mAdapter = new MyBaseAdapter(this, R.layout.my_message_item, map, 5);
        mPullRecyclerView.setAdapter(mAdapter);

        mDatas = new ArrayList<>();
        //放入客服消息
        MessageItem model = new MessageItem();
        model.setTitle("客服消息");
        model.setSubTitle("1");
        model.setMessage("你好,很高兴为您服务");
        model.setImageResId(R.mipmap.message_service);
        mDatas.add(model);
        model = new MessageItem();
        model.setTitle("系统消息");
        model.setImageResId(R.mipmap.message_system);
        mDatas.add(model);
        mAdapter.addAll(mDatas);
        // 设置下拉刷新的旋转圆圈的颜色
        mPullRecyclerView.setColorSchemeResources(R.color.appBlue);
        // 开启下拉刷新，默认即为true，可不用设置
        mPullRecyclerView.enablePullRefresh(false);

        //刷新监听
        mPullRecyclerView.setOnRecyclerRefreshListener(new PullRecyclerView.OnRecyclerRefreshListener() {
            @Override
            public void onPullRefresh() {
                // 下拉刷新网络请求
                Callback.Cancelable drawCallBack = App.getApp().getHttpTools().SystemMessageList("1", "10", CallBackDown);
                App.getApp().getHttpTools().getStandInsidLetterInfoList("1","1",standInsideLetterCallBack);
                RequestTools.addNewRequest(MessageListActivity.class.getName(), drawCallBack);
            }

            @Override
            public void onLoadMore() {
            }
        });
        mPullRecyclerView.autoRefresh();
        mPullRecyclerView.enablePullRefresh(true);
        // 通过adapter设置item的点击事件
        mAdapter.setOnRecyclerItemClickListener((view, position) ->  {

                switch (position) {
                    case 0:
                        CustomServiceUtil customServiceUtil = new CustomServiceUtil();
                        MQImage.setImageLoader(new MQGlideImageLoader4());
                        Intent customeServiceIntent = new MQIntentBuilder(MessageListActivity.this)
                                .setClientInfo(customServiceUtil.queryConfig())
                                .build();
                        startActivity(customeServiceIntent);
                        break;
                    case 1:
                        Intent intent = new Intent(getActivity(), SysteMessageListActivity.class);
                        startActivity(intent);
                        break;
                    default:
                        showToast("暂无服务!");
                        break;
                }
        });
    }

    @Override
    public void onUserLogin(LoginMessage loginMessage) {

    }

    @Override
    public void setBackButtonFinish() {
        if (ivBack != null) {
            ivBack.setOnClickListener(v -> finish());
        }
    }

    RequestCallBack<String> CallBackDown = new RequestCallBack<String>() {

        @Override
        public void onSuccess(String result) {
            if (activityIsDestory()) {
                return;
            }
            try {
                //json解析
                SystemMessageListModel messageListModel = JSON.parseObject(result, SystemMessageListModel.class);
                if (messageListModel != null) {
                    //有数据
                    if (messageListModel.getStatus() == 1) {
                        List<SystemMessageListModel.DataBean.ListBean> mNetDatas = messageListModel.getData().getList();
                        if(mNetDatas != null && mNetDatas.size() > 0){
                            SystemMessageListModel.DataBean.ListBean listBean = mNetDatas.get(0);
                            MessageItem messageItem = mDatas.remove(1);
                            messageItem.setMessage(listBean.getMsg_title());
                            mAdapter.set(1,messageItem);
                        }
                    }
                } else {
                }
            } catch (Exception ex) {

            }
        }

        @Override
        public void onError(Throwable ex, boolean isOnCallback) {

        }

        @Override
        public void onCancelled(Callback.CancelledException cex) {

        }

        @Override
        public void onFinished() {

            if(activityIsDestory()){
                return;
            }
            mPullRecyclerView.stopRefresh();
        }
    };
    RequestCallBack<String> standInsideLetterCallBack = new RequestCallBack<String>() {
        @Override
        public void onSuccess(String result) {
            if (activityIsDestory()) {
                return;
            }
            try {
                //json解析
                StandLetterInfo standLetterInfo = JSON.parseObject(result, StandLetterInfo.class);
                    //有数据
                    if (standLetterInfo != null && standLetterInfo.getStatus() == 1) {
                        List<StandLetterInfo.ListBean> mNetDatas = standLetterInfo.getList();
                        if(mNetDatas != null && mNetDatas.size() > 0){
                            StandLetterInfo.ListBean listBean = mNetDatas.get(0);
                            MessageItem messageItem = mDatas.remove(2);
                            messageItem.setMessage(listBean.getTitle());
                            mAdapter.set(2,messageItem);
                        }
                    }
            } catch (Exception ex) {

            }
        }

        @Override
        public void onError(Throwable ex, boolean isOnCallback) {

        }

        @Override
        public void onCancelled(Callback.CancelledException cex) {

        }

        @Override
        public void onFinished() {

        }
    };
    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 清空请求
        RequestTools.removeRequest(MessageListActivity.class.getName());

        if (unbinder != null) {
            unbinder.unbind();
        }
    }
}
